package com.feige.utils.file.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.feige.utils.file.FsUtils;
import com.feige.utils.file.pojo.AliyunOssProperties;
import com.feige.utils.file.pojo.FSInfo;
import com.feige.utils.file.FileUdService;
import com.feige.utils.file.pojo.UploadInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @description: 阿里云工具类
 * @author: feige
 * @date: 2021/9/24 17:21
 */
public class OssFileUdServiceImpl implements FileUdService {

    Logger logger = LoggerFactory.getLogger(OssFileUdServiceImpl.class);

    private final AliyunOssProperties aliyunOssProperties;

    public OssFileUdServiceImpl(AliyunOssProperties aliyunOssProperties) {
        this.aliyunOssProperties = aliyunOssProperties;
    }

    /**
     * 上传文件到阿里云oss
     * @param uploadInfo 文件上传信息对象
     * @return com.feige.pojo.FSInfo 文件存储信息对象
     */
    @Override
    public FSInfo upload(UploadInfo uploadInfo) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder()
                    .build(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
            // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
            String group = "oss/" + uploadInfo.getFileType() + (uploadInfo.isEnableDatePath() ? "/" + FsUtils.joinFileName() : "");
            ossClient.putObject(aliyunOssProperties.getBucketName(), group + "/" + uploadInfo.getFullFileName(), uploadInfo.getInputStream());
            FSInfo fsInfo = new FSInfo();
            fsInfo.setPath(uploadInfo.getFullFileName());
            fsInfo.setGroup(group);
            fsInfo.setStorageType(getType());
            fsInfo.setOriginalFilename(uploadInfo.getOriginalFilename());
            logger.info("{}文件上传成功",uploadInfo.getFileName());
            return fsInfo;
            // 关闭OSSClient。
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * 从oss获取文件输入流
     * @param objectName 文件路径
     * @return 输入流
     */
    @Override
    public InputStream getFileInputStream(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());
        try {
            OSSObject object = ossClient.getObject(aliyunOssProperties.getBucketName(), objectName);
            return object.getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        throw new RuntimeException("下载文件出错");
    }

    @Override
    public String getType() {
        return FsUtils.OSS;
    }


}
